package com.zunipe.accounts.fragment;

import static android.content.Context.RECEIVER_NOT_EXPORTED;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zunipe.accounts.R;
import com.zunipe.accounts.database.handler.AccountHandler;
import com.zunipe.accounts.databinding.FragmentAccountBinding;
import com.zunipe.accounts.ui.AccountAdapter;
import com.zunipe.accounts.util.DateUtils;

import java.util.Locale;

public class AccountFragment extends Fragment implements View.OnClickListener {
    FragmentAccountBinding binding;
    private String date;
    private AccountAdapter adapter;
    private AccountHandler accountHandler;
    private BroadcastReceiver broadcastReceiver;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentAccountBinding.inflate(inflater, container, false);
        date = DateUtils.getMonth(System.currentTimeMillis());
        accountHandler = new AccountHandler();
        RecyclerView recyclerView = binding.accountList;
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
        adapter = new AccountAdapter(date);
        recyclerView.setAdapter(adapter);
        update();

        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                update();
            }
        };
        requireActivity().registerReceiver(broadcastReceiver, new IntentFilter("com.zunipe.accounts.update.list"), RECEIVER_NOT_EXPORTED);

        binding.tvYear.setOnClickListener(this);
        binding.tvMonth.setOnClickListener(this);
        return binding.getRoot();
    }

    public void update() {
        if (adapter != null) {
            adapter.update(date);
            binding.tvExpensesNumber.setText(String.valueOf(accountHandler.getExpensesAmountByDate(date)));
            binding.tvIncomeNumber.setText(String.valueOf(accountHandler.getIncomeAmountByDate(date)));
            binding.tvYear.setText(DateUtils.getYear(date) + "年");
            binding.tvMonth.setText(DateUtils.getMonth(date) + "月");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        requireActivity().unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_year || id == R.id.tv_month) {
            View view = getLayoutInflater().inflate(R.layout.custom_date_picker, null);
            NumberPicker year = view.findViewById(R.id.numberPickerYear);
            NumberPicker month = view.findViewById(R.id.numberPickerMonth);
            year.setMinValue(1900); // 起始年份
            year.setMaxValue(2100); // 结束年份，根据需要调整
            year.setValue(Integer.parseInt(DateUtils.getYear(date))); // 默认值设为当前年份
            year.setWrapSelectorWheel(false); // 禁止循环选择
            month.setMinValue(1); // 月份从1开始（即1月）
            month.setMaxValue(12); // 12个月
            month.setValue(Integer.parseInt(DateUtils.getMonth(date)));
            AlertDialog dialog = new AlertDialog.Builder(requireActivity())
                    .setView(view)
                    .setTitle("选择日期")
                    .setPositiveButton("确定", (dialog1, which) -> {
                        date = String.format(Locale.CHINA, "%d-%02d", year.getValue(), month.getValue());
                        update();
                    })
                    .setNegativeButton("取消", null)
                    .create();
            dialog.show();
        }
    }
}
